﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ufida.u9.ait.openapi.utils;
using UFIDA.U9.Base;
using UFIDA.U9.Base.BaseBE.ValueSetDefBE;
using UFIDA.U9.Base.Currency;
using UFIDA.U9.Base.Organization;
using UFIDA.U9.CBO.FI.BankAccount;
using UFIDA.U9.CBO.FI.CashAccount;
using UFIDA.U9.CBO.FI.IncExpItem;
using UFIDA.U9.CBO.FI.SettlementMethod;
using UFIDA.U9.CBO.HR.Person;
using UFIDA.U9.ER.LoanBill;
using UFIDA.U9.ER.LoanPaying;
using UFIDA.U9.ER.LoanPayingBP;
using UFSoft.UBF.Business;

namespace ufida.u9.ait.openapi
{
    internal class LoanPayingBase
    {
        public static LoanPaying DeleteDoc(LoanPaying doc)
        {
            if (doc == null) return null;
            doc = doc.Key.GetEntity();

            if(doc.Status== LoanPayingEnum.Approved)
            {
                //弃审
                UnApproveDoc(doc);
            }

            //删除
            using (ISession session = Session.Open())
            {
                doc.Remove();
                session.Commit();
            }
            return doc;
        }

        public static LoanPaying SubmitDoc(LoanPaying doc)
        {
            doc = doc.Key.GetEntity();

            if (doc.Status != LoanPayingEnum.Opening)
                throw new Exception($"单号[{doc.DocNo}]状态不为开立,不能提交");

            LoanPayDocSubmitBP bp = new LoanPayDocSubmitBP();
            bp.UiSysVersion = doc.SysVersion;
            bp.DocKey = doc.Key;
            bp.Do();

            return doc;
        }
        public static LoanPaying ApproveDoc(LoanPaying doc)
        {
            doc = doc.Key.GetEntity();

            if (doc.Status != LoanPayingEnum.Approving)
                throw new Exception($"单号[{doc.DocNo}]状态不为提交,不能审核");

            LoanPayDocAuditBP bp = new LoanPayDocAuditBP();
            bp.UiSysVersion=doc.SysVersion;
            bp.LoanPayingKey = doc.Key;
            bp.IsBatchApprove = true;
            bp.Do();

            return doc;
        }

        public static LoanPaying UnApproveDoc(LoanPaying doc)
        {
            doc = doc.Key.GetEntity();

            if (doc.Status != LoanPayingEnum.Approved)
                throw new Exception($"单号[{doc.DocNo}]状态不为已审,不能弃审");

            LoanPayDocUnAuditBP bp = new LoanPayDocUnAuditBP();
            bp.UiSysVersion = doc.SysVersion;
            bp.LoanPayingKey = doc.Key;
            bp.IsBatchUnApprove = true;
            bp.Do();

            return doc;
        }

        public static LoanPaying SaveDoc(LoanPayingAITDTOData dto)
        {
            LoanPaying doc;
            using (ISession session = Session.Open())
            {
                doc = LoanPaying.Create();
                doc.DocNo = "自动编号";
                if (string.IsNullOrEmpty(dto.PayDate)) throw new Exception("PayDate必填");
                doc.PayDate = DateTime.Parse(dto.PayDate);
                if (dto.LoanPayDocType == null) throw new Exception("LoanPayDocType必填");
                doc.LoanPayDocType = EntityUtils.GetEntityByCode<LoanPayingDocType>(dto.LoanPayDocType.Code);

                //组织
                doc.Org = Context.LoginOrg;
                doc.PayOrg = doc.Org;//还款组织
                if (dto.PayOrg != null) 
                { 
                    doc.PayOrg=EntityUtils.GetEntityByCode<Organization>(dto.PayOrg.Code);
                }
                doc.SettleOrg = doc.Org;
                if (dto.SettleOrg!=null)
                {
                    doc.SettleOrg= EntityUtils.GetEntityByCode<Organization>(dto.SettleOrg.Code);
                }

                //还款人
                if (dto.Payer == null) throw new Exception("Payer必填");
                doc.Payer = EntityUtils.GetEntityByPath<EmployeeArchive>($"EmployeeCode='{dto.Payer.Code}'");
                //还款人组织
                doc.PayerOrg = EntityUtils.GetEmployeeOrg(doc.Payer);
                if (doc.PayerOrg==null) throw new Exception($"还款人[{dto.Payer.Code}]不存在主任职业务组织");


                //金额
                doc.PayMny = dto.PayMny;
                doc.PayMidCurMny = dto.PayMny;
                doc.PayLocalCurMny=dto.PayMny;
                doc.LoanMny = dto.PayMny;

                //实体扩展字段
                if (dto.DescFlexField != null)
                {
                    doc.DescFlexField = new UFIDA.U9.Base.FlexField.DescFlexField.DescFlexSegments();
                    DTOUtils.DTOPropCopy(dto.DescFlexField, doc.DescFlexField);
                }

                //银行卡
                doc.BankCardNumber = EntityUtils.GetEntityByCommon<EmployeeBankAccount>(dto.BankCardNumber);
                if (doc.BankCardNumber != null)
                {
                    doc.BankCardCategory = doc.BankCardNumber.CardType;
                }

                //其它
                doc.Memo= dto.Memo;
                doc.MidToLocalCurRate = 1;
                doc.LoanToMidCurRate = 1;
                doc.LoanToLocalCurRate = 1;
                doc.WorkFlowID = Guid.Empty;
                doc.StateMachineID= Guid.Empty;
                doc.SOBPeriod = EntityUtils.getPostPeriod(doc.PayDate);
                doc.PayToMidCurRate = 1;
                doc.PayToLocalCurRate = 1;
                doc.PayCurrency = EntityUtils.GetEntityByCode<Currency>("C001");
                doc.MiddleCurrency = doc.PayCurrency;
                doc.LocalCurrency = doc.PayCurrency;
                doc.LoanCurrency = doc.PayCurrency;
                

                //借款行处理
                decimal balanceSum = 0;//借款余额汇总
                decimal loanSum = 0;//冲销金额汇总
                foreach(var linedto in dto.LoanPayingDetail)
                {
                    LoanPayingDetail line = LoanPayingDetail.Create(doc);
                    line.LoanMny = linedto.LoanMny;
                    line.LoanMnyFC = linedto.LoanMny;
                    //查找借款单
                    if(linedto.LoanDoc==null) throw new Exception("LoanDoc必填");
                    LoanBill loanBill = EntityUtils.GetDocEntity<LoanBill>(linedto.LoanDoc.Code);
                    line.LoanDoc = loanBill;
                    line.LoanDocType = loanBill.LoanBillType;
                    line.LoanBalance=loanBill.LoanBalance;
                    line.LoanBalanceFC=loanBill.LoanBalance;

                    balanceSum+= loanBill.LoanBalance;
                    loanSum += linedto.LoanMny;
                }

                //收款行处理
                if (dto.CashierGather != null)
                {
                    int rowno = 0;
                    foreach (var linedto in dto.CashierGather)
                    {
                        if (linedto.GatherMny == 0) continue;

                        rowno += 10;
                        CashierGather line = CashierGather.Create(doc);
                        line.RowMark = rowno;
                        //结算方式
                        if (linedto.SettleMode == null) throw new Exception("SettleMode必填");
                        line.SettleMode = EntityUtils.GetEntityByCode<SettlementMethod>(linedto.SettleMode.Code);
                        //金额
                        line.GatherMny = linedto.GatherMny;
                        line.GatherLocalCurMny = linedto.GatherMny;
                        //账号
                        line.GatherBankAccount = EntityUtils.GetEntityByCommon<BankAccount>(linedto.GatherBankAccount);
                        line.CashAccount = EntityUtils.GetEntityByCode<CashAccount>(linedto.CashAccount);
                        //其它
                        line.NoteNo = linedto.NoteNo;
                        if (!string.IsNullOrEmpty(linedto.ReturnDate))
                        {
                            line.ReturnDate = DateTime.Parse(linedto.ReturnDate);
                        }
                        line.IncExpItem = EntityUtils.GetEntityByCode<IncExpItem>(linedto.IncExpItem);
                    }
                }

                //表头汇总信息处理
                doc.SumPayMidCurMny = loanSum;
                doc.SumPayCurMny = loanSum;
                doc.SumLoanCurBalance = balanceSum;
                doc.LoanBalance = balanceSum;

                session.Commit();
            }

            //运达项目,清除缓存
            U9Utils.ClearCache();
            doc=doc.Key.GetEntity();
            return doc;
        }
    }
}
